package com.lhh.controller;


import com.alibaba.fastjson.JSONObject;
import com.lhh.core.Result;
import com.lhh.entity.User;
import com.lhh.entity.Validate;
import com.lhh.service.UserService;
import com.lhh.service.ValidateService;
import com.lhh.utils.Md5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "密码重置")
@RestController
@RequestMapping(value = "/validate")
public class ValidateController {

    @Autowired
    private ValidateService validateService;

    @Autowired
    private UserService userService;

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    //密码重置验证码
    String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);

    @ApiOperation(value = "密码重置",notes = "密码重置")
    @RequestMapping(value = "/sendValidationEmail", method = RequestMethod.POST)
    public Result sendValidationEmail(@ApiParam("邮箱地址") @RequestParam("email") String email,
                                      HttpServletRequest request) throws MessagingException {
//        Result result =new Result();
        User user = userService.getUserByEmail(email);
        if(user == null) {
            return Result.fail("不存在该用户");
        }else {
//           if(validateService.sendValidateLimitation(email,20,1)){
               Validate validate = new Validate();
               validateService.insertNewResetRecord(validate,user, UUID.randomUUID().toString());
               String appUrl = request.getScheme() + "://" + request.getServerName()+":"+request.getServerPort();
               MimeMessage mimeMessage = mailSender.createMimeMessage();

               //multipart 模式
               MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "utf-8");
               mimeMessageHelper.setTo(email);
               mimeMessageHelper.setFrom(from);
               mimeMessageHelper.setSubject("重置密码");
               StringBuilder sb = new StringBuilder();
               //邮件文本内容
            /**
               sb.append("");
               sb.append("" +appUrl +"/validate/resetPassword?token="+validate.getToken()+">"+appUrl +"/validate/resetPassword?token=" +validate.getToken()+"");
               sb.append("");
             */
                sb.append("您的密码重置验证码为：" + checkCode);
               //启用html
               mimeMessageHelper.setText(sb.toString(),true);
               validateService.sendpasswordResetEmail(mimeMessage);

               Map map1 = new HashMap<>();
               map1.put("token",validate.getToken());
               map1.put("link",appUrl + "/validate/resetPassword?token=" + validate.getToken());
               map1.put("message","邮件已经发送");
               return Result.success("发送成功",1);
//           }else {
//               return Result.fail("操作过于频繁");
//           }
        }

        }

//    @ApiOperation(value = "验证码验证",notes = "验证码验证")
//    @RequestMapping(value = "/check",method = RequestMethod.POST)
//    @ResponseBody
//    public Result check(String verifyCOde) {
//        if(verifyCOde.equalsIgnoreCase(checkCode)){
//            return Result.success("验证码正确",1);
//        }else {
//            return Result.fail("验证码错误");
//        }
//    }

    @ApiOperation(value = "修改密码",notes = "修改密码")
    @RequestMapping(value = "/updatapasswd",method = RequestMethod.POST)
    @ResponseBody
    public Result updatapasswd( @RequestParam String verifyCode,
                                @RequestParam String email,
                                @RequestParam String newpasswd) {
        if (!verifyCode.equalsIgnoreCase(checkCode)) {
            return Result.fail("验证码错误");
        }
        if(StringUtils.isEmpty(newpasswd)) {
            return Result.fail("密码不能为空");
        }
        User exsitUser = userService.getUserByEmail(email);
        SimpleDateFormat modifyDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = modifyDate.format(new Date());
        exsitUser.setPasswd(newpasswd);
        exsitUser.setToken(Md5Util.MD5(newpasswd));
        exsitUser.setUpdateTime(format);
        int count = userService.modifypassword(exsitUser);
        if(count !=1) {
            Result.fail("修改密码失败");
        }
        return Result.success("重置成功",1);
    }
}
